<?php
namespace system\libraries\files;

/**
 * Description of File
 *
 * @author Steffen Brem <steffenbrem@gmail.com>
 */
class File 
{
    private $_fileName;
    
    /**
     * Stores the file handler
     */
    private $_readHandler;
    
    /**
     * Stores the write handler
     */
    private $_writeHandler;
    
    /**
     * Constructor
     * 
     * @param type $name 
     */
    public function __construct( $fileName )
    {
        $this->_fileName = $fileName;
        
        if ( ! file_exists($this->_fileName) )
        {
            throw new \Exception('Could not open "' . $this->_fileName . '". File does not exist.');
        }
    }
    
    /**
     *
     *  @return string 
     */
    public function getFileName()
    {
        return $this->_fileName;
    }
    
    /**
     * Read the file
     * 
     * @return string 
     */
    public function read()
    {
        if ( ! $this->_readHandler )
        {
            $this->_readHandler = fopen($this->_fileName, 'r');
        }
        
        return fread( $this->_readHandler, 99999 );
    }
    
    /**
     * Write a line to the file
     * 
     * @param string $text 
     */
    public function write( $text, $mode = 'w' )
    {
        if ( ! $this->_writeHandler )
        {
            $this->_writeHandler = fopen($this->_fileName, $mode);
        }
        
        return ( fwrite($this->_writeHandler, $text) ) ? TRUE : FALSE;
    }
}